{% extends "base.html" %}

{% block title %}XBot管理后台 - 群聊管理{% endblock %}

{% block page_title_icon %}<i class="bi bi-people page-title-icon"></i>{% endblock %}
{% block page_title %}群聊管理{% endblock %}

{% block content %}
<!-- 操作区域 -->
<div class="row mb-4">
    <div class="col-md-8">
        <div class="input-group">
            <input type="text" class="form-control" placeholder="搜索群聊..." id="searchInput">
            <button class="btn btn-primary" type="button" id="searchBtn">
                <i class="bi bi-search"></i> 搜索
            </button>
        </div>
    </div>
    <div class="col-md-4 text-end">
        <button class="btn btn-primary" id="refreshBtn">
            <i class="bi bi-arrow-clockwise"></i> 刷新列表
        </button>
    </div>
</div>

<!-- 群聊统计卡片 -->
<div class="row mb-4">
    <div class="col-md-4 mb-3">
        <div class="card">
            <div class="card-body d-flex align-items-center">
                <div class="flex-shrink-0 icon-wrapper bg-primary-light">
                    <i class="bi bi-people text-primary"></i>
                </div>
                <div class="flex-grow-1 ms-3">
                    <div class="small text-muted">总群聊数</div>
                    <div class="fw-bold fs-4" id="totalGroups">--</div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-4 mb-3">
        <div class="card">
            <div class="card-body d-flex align-items-center">
                <div class="flex-shrink-0 icon-wrapper bg-success-light">
                    <i class="bi bi-person-check text-success"></i>
                </div>
                <div class="flex-grow-1 ms-3">
                    <div class="small text-muted">总成员数</div>
                    <div class="fw-bold fs-4" id="totalMembers">--</div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-4 mb-3">
        <div class="card">
            <div class="card-body d-flex align-items-center">
                <div class="flex-shrink-0 icon-wrapper bg-info-light">
                    <i class="bi bi-clock-history text-info"></i>
                </div>
                <div class="flex-grow-1 ms-3">
                    <div class="small text-muted">最近更新</div>
                    <div class="fw-bold" id="lastUpdate">--</div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 群聊列表 -->
<div class="card">
    <div class="card-header">
        <h5 class="card-title mb-0">群聊列表</h5>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light">
                    <tr>
                        <th>群名称</th>
                        <th>群ID</th>
                        <th>成员数</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="groupsTableBody">
                    <tr>
                        <td colspan="5" class="text-center py-4">
                            <div class="spinner-border text-primary" role="status"></div>
                            <p class="mt-2 text-muted">加载中...</p>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 群聊详情模态框 -->
<div class="modal fade" id="groupDetailModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">群聊详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="groupDetailContent">
                    <div class="text-center py-4">
                        <div class="spinner-border text-primary" role="status"></div>
                        <p class="mt-2">加载中...</p>
                    </div>
                </div>
                
                <div class="mt-4">
                    <h5 class="mb-3">群成员列表</h5>
                    <div class="table-responsive">
                        <table class="table table-sm table-hover">
                            <thead class="table-light">
                                <tr>
                                    <th>昵称</th>
                                    <th>微信ID</th>
                                    <th>角色</th>
                                </tr>
                            </thead>
                            <tbody id="groupMembersTableBody">
                                <tr>
                                    <td colspan="3" class="text-center py-4">
                                        <div class="spinner-border spinner-border-sm text-primary" role="status"></div>
                                        <span class="ms-2">加载中...</span>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

{% block scripts %}
<script>
// 全局变量
let groupsList = [];
let currentGroup = null;
let groupDetailModal = null;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化模态框
    groupDetailModal = new bootstrap.Modal(document.getElementById('groupDetailModal'));
    
    // 加载群聊列表
    loadGroups();
    
    // 绑定事件
    document.getElementById('refreshBtn').addEventListener('click', loadGroups);
    document.getElementById('searchBtn').addEventListener('click', searchGroups);
    document.getElementById('searchInput').addEventListener('keyup', function(e) {
        if (e.key === 'Enter') {
            searchGroups();
        }
    });
});

// 加载群聊列表
async function loadGroups() {
    const tableBody = document.getElementById('groupsTableBody');
    tableBody.innerHTML = `
        <tr>
            <td colspan="5" class="text-center py-4">
                <div class="spinner-border text-primary" role="status"></div>
                <p class="mt-2 text-muted">加载中...</p>
            </td>
        </tr>
    `;
    
    try {
        const response = await fetch('/api/groups');
        const data = await response.json();
        
        if (data.success) {
            groupsList = data.data || [];
            displayGroups(groupsList);
            updateStats(groupsList);
        } else {
            tableBody.innerHTML = `
                <tr>
                    <td colspan="5" class="text-center py-4">
                        <div class="text-danger">
                            <i class="bi bi-exclamation-circle fs-3 mb-3"></i>
                            <p>加载失败: ${data.message || '未知错误'}</p>
                        </div>
                    </td>
                </tr>
            `;
        }
    } catch (error) {
        console.error('加载群聊列表失败:', error);
        tableBody.innerHTML = `
            <tr>
                <td colspan="5" class="text-center py-4">
                    <div class="text-danger">
                        <i class="bi bi-exclamation-circle fs-3 mb-3"></i>
                        <p>加载失败: ${error.message || '网络错误'}</p>
                    </div>
                </td>
            </tr>
        `;
    }
}

// 显示群聊列表
function displayGroups(groups) {
    const tableBody = document.getElementById('groupsTableBody');
    
    if (!groups || groups.length === 0) {
        tableBody.innerHTML = `
            <tr>
                <td colspan="5" class="text-center py-4">
                    <div class="text-muted">
                        <i class="bi bi-people fs-3 mb-3"></i>
                        <p>暂无群聊数据</p>
                    </div>
                </td>
            </tr>
        `;
        return;
    }
    
    let html = '';
    groups.forEach(group => {
        const groupName = group.group_name || '未命名群聊';
        const groupId = group.id || group.qid || '';
        const memberCount = group.member_count || 0;
        const createTime = group.create_time ? new Date(group.create_time * 1000).toLocaleString() : '--';
        
        html += `
            <tr>
                <td>${escapeHtml(groupName)}</td>
                <td><small class="text-muted">${escapeHtml(groupId)}</small></td>
                <td>${memberCount}</td>
                <td>${createTime}</td>
                <td>
                    <button class="btn btn-sm btn-outline-primary" onclick="viewGroupDetail('${groupId}')">
                        <i class="bi bi-info-circle"></i> 详情
                    </button>
                </td>
            </tr>
        `;
    });
    
    tableBody.innerHTML = html;
}

// 更新统计信息
function updateStats(groups) {
    document.getElementById('totalGroups').textContent = groups.length;
    
    // 计算总成员数
    let totalMembers = 0;
    groups.forEach(group => {
        totalMembers += group.member_count || 0;
    });
    document.getElementById('totalMembers').textContent = totalMembers;
    
    document.getElementById('lastUpdate').textContent = new Date().toLocaleString();
}

// 搜索群聊
function searchGroups() {
    const searchTerm = document.getElementById('searchInput').value.toLowerCase();
    
    if (!searchTerm) {
        displayGroups(groupsList);
        return;
    }
    
    const filteredGroups = groupsList.filter(group => {
        const groupName = (group.name || '').toLowerCase();
        const groupId = (group.id || group.qid || '').toLowerCase();
        
        return groupName.includes(searchTerm) || groupId.includes(searchTerm);
    });
    
    displayGroups(filteredGroups);
}

// 查看群聊详情
async function viewGroupDetail(groupId) {
    const detailContent = document.getElementById('groupDetailContent');
    const membersTableBody = document.getElementById('groupMembersTableBody');
    
    detailContent.innerHTML = `
        <div class="text-center py-4">
            <div class="spinner-border text-primary" role="status"></div>
            <p class="mt-2">加载中...</p>
        </div>
    `;
    
    membersTableBody.innerHTML = `
        <tr>
            <td colspan="3" class="text-center py-4">
                <div class="spinner-border spinner-border-sm text-primary" role="status"></div>
                <span class="ms-2">加载中...</span>
            </td>
        </tr>
    `;
    
    // 保存当前群聊ID
    currentGroup = groupId;
    
    // 显示模态框
    groupDetailModal.show();
    
    try {
        const response = await fetch(`/api/groups/${groupId}`);
        const data = await response.json();
        
        if (data.success) {
            const group = data.data.info_detail;
            const groupName = group.NickName.string || '未命名群聊';
            const memberCount = group.NewChatroomData.MemberCount || 0;
            const createTime = group.create_time ? new Date(group.create_time * 1000).toLocaleString() : '--';

            let html = `
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <div class="fw-bold">群名称</div>
                        <div>${escapeHtml(groupName)}</div>
                    </div>
                    <div class="col-md-6 mb-3">
                        <div class="fw-bold">群ID</div>
                        <div>${escapeHtml(groupId)}</div>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <div class="fw-bold">成员数量</div>
                        <div>${memberCount}</div>
                    </div>
                    <div class="col-md-6 mb-3">
                        <div class="fw-bold">创建时间</div>
                        <div>${createTime}</div>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-md-12 mb-3">
                        <div class="fw-bold">群公告</div>
                        <div>${escapeHtml(group.announcement || '--')}</div>
                    </div>
                </div>
            `;
            
            detailContent.innerHTML = html;
            
            // 加载群成员
            if (group.NewChatroomData.ChatRoomMember && group.NewChatroomData.ChatRoomMember.length > 0) {
                displayGroupMembers(group.NewChatroomData.ChatRoomMember,group.ChatRoomOwner);
            }
        } else {
            detailContent.innerHTML = `
                <div class="text-center text-danger">
                    <i class="bi bi-exclamation-circle fs-3 mb-3"></i>
                    <p>加载失败: ${data.message || '未知错误'}</p>
                </div>
            `;
            
            membersTableBody.innerHTML = `
                <tr>
                    <td colspan="3" class="text-center py-4">
                        <div class="text-danger">
                            <p>无法加载群成员</p>
                        </div>
                    </td>
                </tr>
            `;
        }
    } catch (error) {
        console.error('加载群聊详情失败:', error);
        detailContent.innerHTML = `
            <div class="text-center text-danger">
                <i class="bi bi-exclamation-circle fs-3 mb-3"></i>
                <p>加载失败: ${error.message || '网络错误'}</p>
            </div>
        `;
        
        membersTableBody.innerHTML = `
            <tr>
                <td colspan="3" class="text-center py-4">
                    <div class="text-danger">
                        <p>无法加载群成员</p>
                    </div>
                </td>
            </tr>
        `;
    }
}

// 加载群成员
// async function loadGroupMembers(groupId) {
//     const membersTableBody = document.getElementById('groupMembersTableBody');
//
//     try {
//         const response = await fetch(`/api/chat/group/${groupId}/members`);
//         const data = await response.json();
//
//         if (data.success) {
//             displayGroupMembers(data.data || []);
//         } else {
//             membersTableBody.innerHTML = `
//                 <tr>
//                     <td colspan="3" class="text-center py-4">
//                         <div class="text-danger">
//                             <p>加载失败: ${data.message || '未知错误'}</p>
//                         </div>
//                     </td>
//                 </tr>
//             `;
//         }
//     } catch (error) {
//         console.error('加载群成员失败:', error);
//         membersTableBody.innerHTML = `
//             <tr>
//                 <td colspan="3" class="text-center py-4">
//                     <div class="text-danger">
//                         <p>加载失败: ${error.message || '网络错误'}</p>
//                     </div>
//                 </td>
//             </tr>
//         `;
//     }
// }

// 显示群成员
function displayGroupMembers(members,ownerwxid) {
    const membersTableBody = document.getElementById('groupMembersTableBody');
    
    if (!members || members.length === 0) {
        membersTableBody.innerHTML = `
            <tr>
                <td colspan="3" class="text-center py-4">
                    <div class="text-muted">
                        <p>暂无成员数据</p>
                    </div>
                </td>
            </tr>
        `;
        return;
    }
    
    let html = '';
    members.forEach(member => {
        const nickname = member.NickName || '未知';
        const wxid = member.UserName || '';
        
        // 确定角色
        let role = '成员';
        let roleClass = 'text-muted';
        
        if (wxid===ownerwxid) {
            role = '群主';
            roleClass = 'text-danger';
        }
        
        html += `
            <tr>
                <td>${escapeHtml(nickname)}</td>
                <td><small class="text-muted">${escapeHtml(wxid)}</small></td>
                <td><span class="${roleClass}">${role}</span></td>
            </tr>
        `;
    });
    
    membersTableBody.innerHTML = html;
}

// 转义HTML
function escapeHtml(text) {
    if (!text) return '';
    return text
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}
</script>

<style>
.icon-wrapper {
    width: 48px;
    height: 48px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 12px;
    font-size: 1.5rem;
}

.bg-primary-light {
    background-color: rgba(67, 97, 238, 0.1);
}

.bg-success-light {
    background-color: rgba(16, 185, 129, 0.1);
}

.bg-info-light {
    background-color: rgba(59, 130, 246, 0.1);
}
</style>
{% endblock %}
{% endblock %} 